<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="search" label="关键字">
          <el-input
            v-model="queryParams.search"
            placeholder="产品料号，品名，型号，图号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
        </div>
      </div>
      <vxe-grid v-bind="gridOptions">
        <template #pager>
          <!--使用 pager 插槽-->
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handlePageChange"
          />
        </template>
        <template #operate="scope">
          <el-button type="primary" link size="small" @click="handleOpenDialog(scope.row.id)">
            编辑
          </el-button>
          <el-button type="danger" link size="small" @click.stop="handleStatusChange(scope.row)">
            {{ scope.row.status == 1 ? "冻结" : "激活" }}
          </el-button>
          <el-button type="primary" link size="small" @click.stop="handleOpenBOM(scope.row)">
            下级
          </el-button>
          <br />
          <el-button type="primary" link size="small" @click.stop="handleOpenBOM(scope.row)">
            上级
          </el-button>
          <el-button type="primary" link size="small" @click.stop="handleOpenIE(scope.row)">
            资源
          </el-button>
          <el-button type="primary" link size="small" @click.stop="handleOpenIE(scope.row)">
            管制计划
          </el-button>
        </template>
        <template #status="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
            {{ scope.row.status == 1 ? "正常" : "禁用" }}
          </el-tag>
        </template>
        <template #time="scope">
          {{ formatDate(scope.row[scope.column.field]) }}
        </template>
      </vxe-grid>

      <!-- 用户表单 -->
      <el-drawer
        v-model="dialog.visible"
        :title="dialog.title"
        append-to-body
        @close="handleCloseDialog"
      >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
          <el-form-item label="料号" prop="id">
            <el-input v-model="formData.id" placeholder="料号" :disabled="formData.is_update" />
          </el-form-item>
          <el-form-item label="品名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入品名" />
          </el-form-item>
          <el-form-item label="区分描述" prop="title">
            <el-input v-model="formData.title" placeholder="请输入区分描述" />
          </el-form-item>
          <el-form-item label="生产厂家" prop="company">
            <el-input v-model="formData.company" placeholder="请输入生产厂家" />
          </el-form-item>
          <el-form-item label="交货单位" prop="unit">
            <el-select v-model="formData.unit" filterable placeholder="请选择单位">
              <el-option
                v-for="item in DictDataOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="单重" prop="weight">
            <el-input v-model="formData.weight" placeholder="请输入单重(g)" />
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input v-model="formData.price" placeholder="请输入价格" />
          </el-form-item>
          <el-form-item>
            <template #label>
              <div class="flex-y-center">客户信息</div>
            </template>

            <div
              v-if="!formData.customer_product_set || formData.customer_product_set.length === 0"
            >
              <el-button
                type="success"
                plain
                @click="formData.customer_product_set = [{ company: '', dwg: '' }]"
              >
                添加客户信息
              </el-button>
            </div>

            <div v-else>
              <div v-for="(item, index) in formData.customer_product_set" :key="index">
                <el-input v-model="item.company" placeholder="客户" style="width: 100px" />

                <span class="mx-1">--</span>

                <el-input v-model="item.dwg" placeholder="图号" style="width: 100px" />

                <el-icon
                  v-if="
                    formData.customer_product_set.indexOf(item) ===
                    formData.customer_product_set.length - 1
                  "
                  class="ml-2 cursor-pointer color-[var(--el-color-success)]"
                  style="vertical-align: -0.15em"
                  @click="formData.customer_product_set.push({ company: '', dwg: '' })"
                >
                  <CirclePlusFilled />
                </el-icon>
                <el-icon
                  class="ml-2 cursor-pointer color-[var(--el-color-danger)]"
                  style="vertical-align: -0.15em"
                  @click="
                    formData.customer_product_set.splice(
                      formData.customer_product_set.indexOf(item),
                      1
                    )
                  "
                >
                  <DeleteFilled />
                </el-icon>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
            <el-button @click="handleCloseDialog">取 消</el-button>
          </div>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  name: "Product",
  inheritAttrs: false,
});
import DictDataAPI from "@/api/system/dict-data";
import { formatDate } from "@/utils/tools";
import ProductAPI, { ProductPageVO, ProductPageQuery, ProductForm } from "@/api/product/product";
const total = ref(0);
const queryFormRef = ref(ElForm);
const formRef = ref(ElForm);
const dialog = reactive({
  visible: false,
  title: "新增产品",
});
const formData = reactive<Partial<ProductForm>>({});
const DictDataOptions = ref<OptionType[]>();
const initFormData: Partial<ProductForm> = {
  id: "",
  name: "",
  title: "",
  company: "",
  weight: 0,
  price: 0,
  status: 0,
  // 交货单位,默认为第一个的id
  unit: DictDataOptions.value?.[0]?.value as number,
  is_update: false,
  customer_product_set: [],
};

const rules = reactive({
  id: [
    {
      pattern: /(^[A-Za-z0-9_-]{4,15}$)/,
      message: "请输入产品编号",
      trigger: "blur",
    },
    { required: true, message: "编号不能为空", trigger: "blur" },
  ],
  name: [{ required: true, message: "品名不能为空", trigger: "blur" }],
  title: [{ required: true, message: "区分描述不能为空", trigger: "blur" }],
  company: [{ required: true, message: "生产厂家不能为空", trigger: "blur" }],
  weight: [
    { required: true, message: "单重不能为空", trigger: "blur" },
    {
      pattern: /^([1-9][0-9]*(\.[0-9]{1,4})?|0\.[0-9]{1,4})$/,
      message: "请输入产品单重",
      trigger: "blur",
    },
  ],
  unit: [{ required: true, message: "交货单位不能为空", trigger: "blur" }],
  price: [
    {
      pattern: /^([1-9][0-9]*(\.[0-9]{1,4})?|0\.[0-9]{1,4})$/,
      message: "请输入产品价格",
      trigger: "blur",
    },
  ],
});

const queryParams = reactive<ProductPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const gridOptions = reactive<typeof VxeGridProps<ProductPageVO>>({
  border: true,
  loading: false,
  id: "product",
  columns: [],
  data: [],
  columnConfig: {
    resizable: true,
  },
});

// 列配置
gridOptions.columns = [
  { field: "id", title: "产品编号", treeNode: true, width: 180 },
  { field: "name", title: "产品名称" },
  { field: "title", title: "区分描述" },
  { field: "company", title: "生产厂家" },
  { field: "unit_name", title: "交货单位", width: 80 },
  { field: "weight", title: "单重" },
  { field: "price", title: "价格" },
  { field: "dwgs", title: "图号", width: 100 },
  { field: "barcode", title: "条形码", width: 80 },
  { field: "status", title: "状态", width: 80, slots: { default: "status" } },
  { field: "create_time", title: "建立时间", width: 100, slots: { default: "time" } },
  { field: "update_time", title: "更新时间", width: 100, slots: { default: "time" } },
  { field: "create_user", title: "建立人员", width: 100 },
  { field: "update_user", title: "更新人员", width: 100 },
  { title: "操作", width: 180, slots: { default: "operate" }, fixed: "right" },
];

gridOptions.treeConfig = {
  transform: true,
  rowField: "id",
  parentField: "parent",
  lazy: true,
  hasChild: "has_child",
  async loadMethod({ row }: { row: ProductPageVO }) {
    gridOptions.loading = true;
    // 异步加载子节点
    handleResetQuery();
    queryParams.pageSize = 100;
    queryParams.bom_material_set__product__id = row.id;
    const temp = await ProductAPI.getPage(queryParams);
    gridOptions.loading = false;
    return temp.list;
  },
};
gridOptions.customConfig = {
  enabled: true,
  storage: {
    resizable: true,
  },
};

// 查询
function handleQuery() {
  gridOptions.loading = true;
  ProductAPI.getPage(queryParams)
    .then((data) => {
      gridOptions.data = data.list;
      total.value = data.total;
    })
    .finally(() => {
      gridOptions.loading = false;
    });
}
// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const product_id = formData.id as string;
      if (formData.is_update) {
        ProductAPI.update(product_id, formData)
          .then(() => {
            ElMessage.success("修改产品成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => {
            gridOptions.loading = false;
          });
      } else {
        ProductAPI.add(formData)
          .then(() => {
            ElMessage.success("新增产品成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => {
            gridOptions.loading = false;
          });
      }
    }
  });
}, 1000);
function getOptions() {
  DictDataAPI.getOptions("unit").then((data) => {
    DictDataOptions.value = data;
  });
}

async function handleOpenDialog(id?: string) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改产品";
    formData.is_update = true;
    ProductAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data });
    });
  } else {
    Object.assign(formData, initFormData);
    dialog.title = "新增产品";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formData.id = undefined;
}
// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
}

const handlePageChange: typeof VxePagerEvents.PageChange = ({
  currentPage,
  pageSize,
}: {
  currentPage: number;
  pageSize: number;
}) => {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  handleQuery();
};
// 激活事件，将用户状态进行修改
function handleStatusChange(row: ProductPageVO) {
  const text = row.status == 0 || row.status == 2 ? "启用" : "停用";
  ElMessageBox.confirm(`确认要${text}该产品吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let status = row.status == 0 || row.status == 2 ? 1 : 2;
    ProductAPI.update(row.id, {
      status: status,
    }).then(() => {
      row.status = status;
      ElMessage.success(`${text}成功`);
    });
  });
}

import router from "@/router";
// 打开字典数据
function handleOpenBOM(row: ProductPageVO) {
  router.push({
    path: "/product/bom/",
    query: { product: row.id, title: row.id + " 的材料" },
  });
}
// 打开字典数据
function handleOpenIE(row: ProductPageVO) {
  router.push({
    path: "/product/management/",
    query: { product: row.id, title: row.id + " 生产管理", unit_name: row.unit_name },
  });
}

onMounted(() => {
  getOptions();
  handleQuery();
});
</script>
